<?php

class CategoriasController extends Zend_Controller_Action
{

    public function init()
    {
        Zend_Loader::loadClass('Categorias');
    }

    public function indexAction()
    {
        $categorias = new Categorias();
        $this->view->categorias = $categorias->fetchAll(null,'categoria');
    }

    public function addAction()
    {
        $form = new Application_Form_Categoria();
        $form->submit->setLabel('Adicionar');
        $this->view->form = $form;
        if ($this->getRequest()->isPost()) {
            $formData = $this->getRequest()->getPost();
            if ($form->isValid($formData)) {
                $categoria = $form->getValue('categoria');
                $categorias = new Categorias();
                $categorias->addCategoria($categoria);
                $this->_redirector('index');
            } else {
                $form->populate($formData);
            }
        }
    }

    public function editAction()
    {
        $form = new Application_Form_Categoria();
        $form->submit->setLabel('Salvar');
        $this->view->form = $form;
        if ($this->getRequest()->isPost()) {
            $formData = $this->getRequest()->getPost();
            if ($form->isValid($formData)) {
                $id = (int)$form->getValue('id');
                $categoria = $form->getValue('categoria');
                $categorias = new Categorias();
                $categorias->updateCategoria($id, $categoria);
                $this->_redirect('index');
            } else {
                $form->populate($formData);
            }
        } else
        {
            $id = $this->_getParam('id', 0);
            if ($id > 0) {
                $categorias = new Categorias();
                $form->populate($categorias->getCategoria($id));
            }
        }
    }

    public function deleteAction()
    {
        if ($this->getRequest()->isPost())
        {
            $del = $this->getRequest()->getPost('del');
            if ($del == 'Sim') {
                $id = $this->getRequest()->getPost('id');
                $categorias = new Categorias();
                $categorias->deleteCategoria($id);
            }
                $this->_redirect('index');
        } else {
            $id = $this->_getParam('id', 0);
            $categorias = new Categorias();
            $this->view->categoria = $categorias->getCategoria($id);
        }
    }


}

